package git.soulbgm.filter;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 解决ajax跨域的过滤器
 *
 * @author SoulBGM
 * @date 2020-11-18 10:03:05
 */
@Component
public class DomainFilter implements Filter {
    /**
     * 初始化
     *
     * @param filterConfig 过滤器配置
     * @throws ServletException servlet异常
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 做的过滤器
     *
     * @param req   要求的事情
     * @param res   res
     * @param chain 链
     * @throws IOException      IO异常
     * @throws ServletException servlet异常
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }

    /**
     * 摧毁
     */
    @Override
    public void destroy() {

    }

    /**
     * 过滤器bean注册
     * 解决ajax跨域
     *
     * @return 过滤注册的Bean
     */
    @Bean
    public FilterRegistrationBean<DomainFilter> filterRegistrationBean() {
        FilterRegistrationBean<DomainFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(this);
        List<String> urlPatterns = new ArrayList<>();
        urlPatterns.add("/*");
        registrationBean.setUrlPatterns(urlPatterns);
        return registrationBean;
    }
}
